package com.wangshouyu.plugins.poi.excel.easy;

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;

import java.lang.reflect.Field;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * @author 王守钰
 * @date 2022-01-19 12:58
 * @description LocalDate类型转换器
 */
public class EasyExcelLocalDateConverter implements Converter<LocalDate> {

    /**
     * 默认日期格式
     */
    private static final String DEFAULT_PATTERN = "yyyy-MM-dd";

    @Override
    public Class<LocalDate> supportJavaTypeKey() {
        return LocalDate.class;
    }
 
    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }
 
    @Override
    public LocalDate convertToJavaData(CellData cellData, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        return LocalDate.parse(cellData.getStringValue(), DateTimeFormatter.ofPattern(pattern(excelContentProperty)));
    }
 
    @Override
    public CellData convertToExcelData(LocalDate localDate, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        return new CellData<>(localDate.format(DateTimeFormatter.ofPattern(pattern(excelContentProperty))));
    }

    /**
     * 获取转换格式
     * @param excelContentProperty 参数列
     * @return 格式
     */
    private String pattern(ExcelContentProperty excelContentProperty){
        Field field = excelContentProperty.getField();
        if(null == field){
            return DEFAULT_PATTERN;
        }
        // 获取注解
        ExcelProperty excelProperty = field.getAnnotation(ExcelProperty.class);
        if(null == excelProperty){
            return DEFAULT_PATTERN;
        }
        String format = excelProperty.format();
        return null == format || "".equals(format.trim()) ? DEFAULT_PATTERN : format;
    }
}